# -*- coding: utf-8 -*-
"""
@Time: 2025/1/18 14:35
@Auth: LYQ
@File: user_routes.py
@Note: 用户基础操作相关路由
"""
from flask import Blueprint, request, jsonify
from functools import wraps
import jwt
from datetime import datetime, timedelta
# 配置信息
SECRET_KEY = 'your_secret_key'
TOKEN_EXPIRATION = 24 * 60 * 60  # 24小时过期


def decode_token(token):
    """
    解码JWT令牌
    """
    try:
        # 明确指定算法和验证选项
        payload = jwt.decode(
            token,
            SECRET_KEY,
            algorithms=['HS256'],
            options={
                'verify_exp': True,  # 验证过期时间
                'verify_iat': True,  # 验证签发时间
            }
        )
        return payload
    except jwt.ExpiredSignatureError:
        print("令牌已过期")
        return None
    except jwt.InvalidTokenError as e:
        print(f"无效的令牌: {str(e)}")
        return None
    except Exception as e:
        print(f"令牌解析错误: {str(e)}")
        return None


def token_required(f):
    """
    Token验证装饰器
    """

    @wraps(f)
    def decorated(*args, **kwargs):
        # 获取Authorization头
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({
                "code": 401,
                "message": "缺少Authorization头信息"
            }), 401

        # 验证Bearer格式
        parts = auth_header.split()
        if parts[0].lower() != 'bearer' or len(parts) != 2:
            return jsonify({
                "code": 401,
                "message": "无效的Authorization格式"
            }), 401

        token = parts[1]
        payload = decode_token(token)

        if payload is None:
            return jsonify({
                "code": 401,
                "message": "无效或过期的令牌"
            }), 401

        try:
            # 验证令牌中的必要信息
            if 'user_id' not in payload:
                return jsonify({
                    "code": 401,
                    "message": "令牌缺少用户信息"
                }), 401

            # 验证令牌是否过期
            exp_timestamp = payload.get('exp')
            if exp_timestamp is None:
                return jsonify({
                    "code": 401,
                    "message": "令牌缺少过期时间"
                }), 401

            current_timestamp = datetime.utcnow().timestamp()
            if current_timestamp > exp_timestamp:
                return jsonify({
                    "code": 401,
                    "message": "令牌已过期"
                }), 401

            # 将用户信息添加到请求上下文
            return f(payload['user_id'], *args, **kwargs)

        except Exception as e:
            return jsonify({
                "code": 401,
                "message": f"令牌验证失败: {str(e)}"
            }), 401

    return decorated
from flask import request, jsonify, Blueprint
import time
from backend.services.user_service import register_user, login_user, get_user_profile,generate_token

user_routes = Blueprint('user_routes', __name__)

#【接口1.1.1】POST /user/register    # 用户注册
@user_routes.route('/user/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    email = data.get('email', None)

    user = register_user(username, password, email)
    if user:
        return jsonify({
            "code": 200,
            "message": "用户注册成功",
            "data": user
        }), 200
    else:
        return jsonify({
            "code": 500,
            "message": "注册失败"
        }), 500


#【接口1.1.2】POST /user/login      # 用户登录
# @user_routes.route('/user/login', methods=['POST'])
# def login():
#     data = request.get_json()
#     username = data.get('username')
#     password = data.get('password')
#
#     user = login_user(username, password)
#     if user:
#         return jsonify({
#             "code": 200,
#             "message": "用户登录成功",
#             "data": user
#         }), 200
#     else:
#         return jsonify({
#             "code": 400,
#             "message": "无效的用户名或密码"
#         }), 400

@user_routes.route('/user/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    # 调用业务逻辑层的 login_user 函数验证用户名和密码
    user = login_user(username, password)

    if user:
        # 如果用户验证成功，生成 token
        token = generate_token(user)

        # 返回用户信息和 token
        return jsonify({
            "code": 200,
            "message": "用户登录成功",
            "data": {
                "user": {
                    "user_id": user["user_id"],  # 或者 user["username"]
                    "username": user["username"],
                    "email": user["email"]
                },
                "token": token  # 返回 token
            }
        }), 200
    else:
        return jsonify({
            "code": 400,
            "message": "无效的用户名或密码"
        }), 400


#【接口1.1.3】GET /user/profile     # 获取用户信息
@user_routes.route('/user/profile', methods=['GET'])
@token_required  # 添加token验证装饰器
def profile(user_id):
    user = get_user_profile(user_id)
    if user:
        return jsonify({
            "code": 200,
            "message": "成功获取用户信息",
            "data": user
        }), 200
    else:
        return jsonify({
            "code": 404,
            "message": "找不到该用户"
        }), 404